from pathlib import Path

from rest_framework import serializers

from .models import RunResult, Suite


class SuiteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Suite
        fields = "__all__"


# 这个序列化器的作用是将RunResult模型的实例转换为JSON格式的数据，以便在API中进行传输。
class RunResultSerializer(serializers.ModelSerializer):
    class Meta:
        model = RunResult
        # fields = ("id", "review")  # 使用部分字段
        # fields = "__all__"  # 使用全部字段
        exclude = ["path"]

    # 测试报告路径
    report_url = serializers.SerializerMethodField()
    # 日志路径
    log_url = serializers.SerializerMethodField()

    # 测试用例路径(暂时不做吧,因为我这边实现的是可以上传多少个yaml文件)
    # yaml_case = serializers.SerializerMethodField()

    def get_report_url(self, obj):
        path = (
            obj.path
        )  # upload_yaml_cases\1753759590.3326952_99f071f2-d253-423a-b1a6-4cba29bbc42a
        path_dir = Path(path).name
        report_url = f"/api/suite/static/{path_dir}/report/index.html"
        return report_url

    def get_log_url(self, obj):
        path = (
            obj.path
        )  # upload_yaml_cases\1753759590.3326952_99f071f2-d253-423a-b1a6-4cba29bbc42a
        path_dir = Path(path).name
        log_url = f"/api/suite/static/{path_dir}/logs/pytest.log"
        return log_url
